"*************************************************************************
"启用 pathogen [可选][默认使用]
"*************************************************************************
execute pathogen#infect()
execute pathogen#helptags()
syntax on
filetype plugin indent on

"*************************************************************************
"启用 vundle [可选]
"*************************************************************************
" set nocompatible                  "关闭vi兼容模式
" filetype off                      "必须"
"
" set rtp+=~/.vim/bundle/Vundle.vim "设置包括vundle和初始化相关的运行时路径"
" call vundle#begin()
"
" Plugin 'VundleVim/Vundle.vim'     "必须, 启用vundle管理插件"
"
" "在此增加其他插件，安装的插件需要放在vundle#begin和vundle#end之间"
" "安装github上的插件格式为 Plugin '用户名/插件仓库名'"
" Plugin 'a.vim'
" Plugin 'taglist.vim'
" Plugin 'posva/vim-vue'
" Plugin 'godlygeek/tabular'
" Plugin 'majutsushi/tagbar'
" Plugin 'preservim/nerdtree'
" Plugin 'luochen1990/rainbow'
" Plugin 'flazz/vim-colorschemes'
" Plugin 'jistr/vim-nerdtree-tabs'
" Plugin 'Xuyuanp/nerdtree-git-plugin'
" Plugin 'tiagofumo/vim-nerdtree-syntax-highlight'
" Plugin 'vim-airline/vim-airline'
" Plugin 'vim-airline/vim-airline-themes'
" Plugin 'octol/vim-cpp-enhanced-highlight'
" Plugin 'kien/ctrlp.vim'
" Plugin 'DoxygenToolkit.vim'
" Plugin 'brookhong/cscope.vim'
" Plugin 'scrooloose/nerdcommenter'
" Plugin 'bronson/vim-trailing-whitespace'
" Plugin 'mbbill/undotree'
" Plugin 'tpope/vim-fugitive'
" Plugin 'mhinz/vim-signify'
" Plugin 't9md/vim-choosewin'
" Plugin 'mhinz/vim-startify'
" Plugin 'Chiel92/vim-autoformat'
" Plugin 'lfv89/vim-interestingwords'
" Plugin 'easymotion/vim-easymotion'
" Plugin 'vim-scripts/indentpython.vim'
"
"
" " Plugin 'rhysd/vim-clang-format'
" " Plugin 'mileszs/ack.vim'
" " Plugin 'Shougo/neocomplete.vim'
" " Plugin 'Valloric/YouCompleteMe'
"
"
" call vundle#end()
"
" filetype plugin indent on "必须, 加载vim自带和插件相应的语法和文件类型相关脚本"

"*************************************************************************
"完成配置 vundle
"*************************************************************************

"=========================================================================
"vim 基本功能设置
"=========================================================================
"菜单项高度
set pumheight=10
hi pmenu ctermbg=white
hi pmenu guibg=white

"界面及功能
set nocompatible                "关闭vi兼容模式
set shortmess=ati               "不显示欢迎画面
set guioptions-=m               "隐藏菜单栏
set guioptions-=t               "隐藏工具栏
set guifont=Ubuntu:h20          "字体
au  guienter * simalt ~x        "全屏显示
au  guienter * set t_vb=        "关闭beep
set visualbell t_vb=            "关闭visual bell
set autoread                    "文件在外部被修改时，自动重新读取
set nobackup                    "不生成备份文件
set history=2000                "历史操作的数量
"set t_co=16                    "16位颜色显示
syntax on                       "开启文件类型侦测
syntax enable                   "语法高亮
filetype on                     " 开启文件类型侦测
filetype plugin on              " 根据侦测到的不同类型加载对应的插件

"状态行
set laststatus=2
set statusline=[%F]%y%r%m%*%=[Line:%l/%L,Column:%c][%p%%] "显示文件名：总行数，总的字符数

"编辑
set magic                       "设置魔术
set showmatch                   "显示括号配对情况
set cindent shiftwidth=4        "自动缩进4空格
set shiftwidth=4                "换行时行间交错使用4个空格
set autoindent                  "自动缩进，继承前一行的缩进方式
set smartindent                 "智能自动缩进
"set noautoindent                "自动缩进
set number                      "显示行号
"set noswapfile                 "不产生.swp文件
set tabstop=4                   "设置tab键的宽度
set expandtab                   "空格替换tab
set backspace=2                 "设置退格键可用
set fdm=manual                  "设置手工定义折叠
set wildmenu                    "增强模式中的命令行自动完成操作
set showcmd                     "输入的命令显示
set ruler                       "在编辑过程中，在右下角显示光标位置的状态行
set cursorline                  "突出显示当前行
" set paste                       "粘贴模式
" set cursorcolumn                "突出显示当前列
" autocmd InsertLeave * se nocul  "用浅色高亮当前行
" autocmd InsertEnter * se cul    "用浅色高亮当前行

set foldenable                  "允许折叠
set foldmethod=manual           "手动折叠
set colorcolumn=81              "设置超过80长度提示
" set textwidth=90                "编辑到90个字符后自动折行
set wrap                        "显示自动折行
" set nowrap                    "显示不自动折行
" set mouse=a

" 设置缩进风格
" :0 表示case 比switch 缩进 0 个字符
" =4 缩进case 内的语句
set cinoptions=p0,t0,:4,=4,(0,u0,w1,m1,
" set cinoptions=>4,n-2,{4,^-2,:2,=2,g0,h2,p5,t0,+2,(0,u0,w1,m1,
set cinwords=if,else,switch,case,for,while,do
set cindent

augroup ft_vim
    au!
    au fileType vim set foldmethod=marker
augroup END

"搜索与匹配
set hlsearch                    "开启高亮显示结果
set ignorecase                  "搜索忽略大小写
" set smartcase                   "智能大小写敏感 有大写时敏感否则不敏感

"编码方式
set enc=utf-8                   "Vim内部使用的编码方式，包括buffer、菜单、消息文本等
" set ffs=unix                    "设置文件格式
set tenc=utf-8                  "Vim所工作的终端的编码方式
set fencs=utf-8,chinese         "fenc的顺序列表(chinese是别名，在Unix表示gb2312，Windows表示cp936，GBK的代码页),
"Vim当前编辑文件的字符编码方式，保存时会设置为该编码；不设置保持文件默认编码
if has("win32")
    set ffs=dos
    set tenc=cp936
    language messages zh_CN.utf-8   "console输出乱码
    set langmenu=zh_CN.utf-8        "中文菜单乱码
    source $VIMRUNTIME/delmenu.vim  "中文菜单乱码
    source $VIMRUNTIME/menu.vim     "中文菜单乱码
endif

" Python 文件的配置
au BufNewFile,BufRead *.py
            \ set tabstop=4 | set softtabstop=4 | set shiftwidth=4 |
            \ set textwidth=79 | set expandtab | set autoindent | set fileformat=unix

"JavaScript、HTML 和 CSS 文件的配置
au BufNewFile,BufRead *.js, *.html, *.css
            \ set tabstop=2 | set softtabstop=2 | set shiftwidth=2

"上一次编辑位置
au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g`\"" | endif

"=========================================================================
" vim 插件管理与配置
"=========================================================================

let mapleader=","     " 定义快捷键的前缀，即<Leader>

"----------------------------------------
"Colorschemes
"----------------------------------------
set t_Co=256 " required
" colorscheme  Tomorrow-Night-Eighties
colorscheme  Tomorrow-Night-Bright
" colorscheme  Tomorrow-Night
" colorscheme  Tomorrow
" colorscheme  peaksea
" colorscheme  molokai
" colorscheme  Monokai
" colorscheme  3dglasses
" colorscheme  widower

"----------------------------------------
" 解决tmux和vim主题冲突
"----------------------------------------
set background=dark

"在profile如.zshrc或.bashrc中添加
"alias tmux="tmux -2"

"----------------------------------------
"airline.vim
"----------------------------------------
let g:airline_powerline_fonts = 0
let g:airline_theme='tomorrow'
let g:airline#extensions#tabline#enabled         = 1
" let g:airline#extensions#tabline#tab_nr_type     = 1 " tab number
" let g:airline#extensions#tabline#show_tab_nr     = 1
" let g:airline#extensions#tabline#formatter       = 'default'
" let g:airline#extensions#tabline#buffer_nr_show  = 0
" let g:airline#extensions#tabline#fnametruncate   = 16
" let g:airline#extensions#tabline#fnamecollapse   = 2
let g:airline#extensions#tabline#buffer_idx_mode = 1
map <c-l> :bnext<CR>  "切换tab

"----------------------------------------
"vim-cpp-enhanced-highlight.vim
"----------------------------------------
let g:cpp_class_scope_highlight = 1
let g:cpp_member_variable_highlight = 1
let g:cpp_class_decl_highlight = 1
let g:cpp_experimental_simple_template_highlight = 1
let g:cpp_experimental_template_highlight = 1
let g:cpp_concepts_highlight = 1
" let g:cpp_no_function_highlight = 1

"----------------------------------------
"a.vim
"----------------------------------------
nnoremap <silent> <F4> :A<CR>

"----------------------------------------
"Taglist
"----------------------------------------
let Tlist_Show_One_File           = 1
let Tlist_Sort_Type               = "name"
let Tlist_Exit_OnlyWindow         = 1
let Tlist_GainFocus_On_ToggleOpen = 1
let Tlist_Show_Menu               = 1
let Tlist_Auto_Open               = 0
let Tlist_Use_Right_Window        = 1   "在Vim窗口右侧显示taglist窗口
" let Tlist_WinWidth         = 40
" let Tlist_Use_Horiz_Window = 1
" let Tlist_WinHeight        = 30
"
nnoremap <silent> <F2> :Tlist<CR>
nnoremap <C-j> <C-]>

"----------------------------------------
"tagbar快捷键
"----------------------------------------
"启动时自动focus
" let g:tagbar_autofocus = 1
" let g:tagbar_ctags_bin = 'ctags' "tagbar以来ctags插件
" let g:tagbar_left      = 1       "让tagbar在页面左侧显示，默认右边
" let g:tagbar_width     = 30      "设置tagbar的宽度为30列，默认40
" let g:tagbar_autofocus = 1       "这是tagbar一打开，光标即在tagbar页面内，默认在vim打开的文件内
" let g:tagbar_sort      = 0       "设置标签不排序，默认排序

let g:tagbar_vertical    = 24      " 在这儿设定二者的分布
let g:tagbar_compact     = 1       " 去除第一行的帮助信息
let g:tagbar_autoshowtag = 1       " 当编辑代码时，在Tagbar自动追踪变量
" wincmd l
autocmd VimEnter * wincmd l        "如果不加这句，打开vim的时候当前光标会在Nerdtree区域

" nmap <silent> <F2> :TagbarToggle<CR>   "按F2即可打开tagbar界面

"----------------------------------------
"移动分割窗口
"----------------------------------------
" nmap <C-h> <C-W><C-W>
nmap <leader>h <C-W><C-W>
nmap <leader>v <C-W>v
nmap <leader>s <C-W>s

"----------------------------------------
"doxygen toolkit
"----------------------------------------
let g:DoxygenToolkit_briefTag_funcName = "yes"
let g:DoxygenToolkit_commentType="C"
" let g:DoxygenToolkit_blockHeader="***************************************************************************"
" let g:DoxygenToolkit_blockFooter="***************************************************************************"
let g:DoxygenToolkit_licenseTag  ="Copyright (C) 2018 http://www.yeelight.com\<enter>" " Lincese
let g:DoxygenToolkit_fileTag     ="@file     -- "
let g:DoxygenToolkit_dateTag     ="@date     -- "
let g:DoxygenToolkit_briefTag_pre="@brief    -- "
let g:DoxygenToolkit_paramTag_pre="@param[ ] -- "
let g:DoxygenToolkit_returnTag   ="@return   -- "
let g:DoxygenToolkit_authorTag   ="@author   -- "
let g:DoxygenToolkit_authorName  ="liuwming  liuwmingw@gmail.com"
let g:DoxygenToolkit_versionTag  ="@version  -- "
let g:DoxygenToolkit_blockTag    ="@name     -- "
let g:DoxygenToolkit_classTag    ="@class    -- "
let g:DoxygenToolkit_briefTag_funcName="yes"
let g:DoxygenToolkit_compactDoc  ="yes"    "insert white line

"----------------------------------------
"nerdcommenter设置
"----------------------------------------

let g:NERDSpaceDelims            = 1      " Add spaces after comment delimiters by default
let g:NERDCompactSexyComs        = 1      " Use compact syntax for prettified multi-line comments
let g:NERDDefaultAlign           = 'left' " Align line-wise comment delimiters flush left instead of following code indentation
let g:NERDAltDelims_java         = 1      " Set a language to use its alternate delimiters by default
let g:NERDCustomDelimiters       = { 'c': { 'left': '/*','right': '*/' } } " Add your own custom formats or override the defaults
let g:NERDCommentEmptyLines      = 1 " Allow commenting and inverting empty lines (useful when commenting a region)
let g:NERDTrimTrailingWhitespace = 1 " Enable trimming of trailing whitespace when uncommenting

"----------------------------------------
"ctrlp快捷键
"----------------------------------------
let g:ctrlp_map = '<c-p>'
let g:ctrlp_cmd = 'CtrlP'

"缓存优先查找
map <S-p> :CtrlPMRU<CR>

"设置过滤不进行查找的后缀名
let g:ctrlp_custom_ignore = {
            \ 'dir':  '\v[\/]\.(git|hg|svn)$',
            \ 'file': '\v\.(o|d|bin|exe|so|dll|zip|tar|tar.gz|pyc)$',
            \ }
let g:ctrlp_match_window_reversed=0
" let g:ctrlp_working_path_mode=0

" let g:ctrlp_working_path_mode = 'ra'
" let g:ctrlp_mruf_max=500
" let g:ctrlp_match_window_bottom=1
" let g:ctrlp_max_height=15
" let g:ctrlp_follow_symlinks=1
let g:ctrlp_user_command = 'ag %s -l --nocolor --hidden -g ""'

"----------------------------------------
"Tabularize
"----------------------------------------
nnoremap <leader>= :Tabularize /
nnoremap <leader>: :Tabularize /:\zs<CR>

"----------------------------------------
"ctags
"----------------------------------------
set hidden                      "放在buffer里不保存
set autochdir

" it tells Vim to look for a tags file in the directory of the current file,
" in the current directory and up and up until your $HOME (that's the meaning of the semicolon),
" stopping on the first hit.
set tags=./tags,tags;$HOME
" set tags=tags;/ "告诉在每个目录下如果找不到tags就到上一层目录去找
"
"nnoremap <F5> :!ctags -R * --languages=c++ --langmap=c++:+.cpp+.cc+.h -h +.h --c++-kinds=+plx --fields=+aiKSzms --extra=+q<CR>

"----------------------------------------
"OmniCppComplete
"----------------------------------------
"set completeopt=longest,menu  " 取消补全内容以分割子窗口形式出现，只显示补全列表
set completeopt=menu,menuone,longest
let OmniCpp_NamespaceSearch     = 1 " 打开命名空间
let OmniCpp_GlobalScopeSearch   = 1
let OmniCpp_ShowAccess          = 1
let OmniCpp_ShowPrototypeInAbbr = 1 " 打开显示函数原型
let OmniCpp_MayCompleteDot      = 1 " 打开  . 操作符
let OmniCpp_MayCompleteArrow    = 1 " 打开 -> 操作符
let OmniCpp_MayCompleteScope    = 1 " 打开 :: 操作符
let OmniCpp_SelectFirstItem     = 2 " 自动弹出时自动跳至第一个
let OmniCpp_DefaultNamespace    = ["std", "_GLIBCXX_STD"]

autocmd BufRead scp://* :set bt=acwrite

"python设置
autocmd filetype python set expandtab

"java设置
autocmd filetype java setlocal omnifunc=javacomplete#complete

" 添加自动补全字典
au FileType cpp setlocal dict+=~/.vim/dictionary/cpp_keywords_list.txt
" au FileType markdown setlocal dict+=~/.vim/dictionary/words.txt

"----------------------------------------
"cscope.vim
"----------------------------------------
" set quickfix
set cscopequickfix=s-,c-,d-,i-,t-,e-
" use both cscope and ctag for 'ctrl-]', ':ta', and 'vim -t'
set cscopetag
" check cscope for definition of a symbol before checking ctags: set to 1
" if you want the reverse search order.
set csto=0
" show msg when any other cscope db added
set cscopeverbose

" cscope 自动加载cscope.out文件
if has("cscope")
    " set csprg=/usr/bin/cscope
    set csto=0
    set cst
    " set csverb
    set nocsverb
    set cspc=3
    "add any database in current dir
    if filereadable("cscope.out")
        let cscope_file = findfile("cscope.out", ".;")
        let cscope_pre  = system("pwd")
        let cscope_pre  = strpart(cscope_pre,0,strlen(cscope_pre) - 1)
        " echo "cs file:" cscope_file
        " echo "cs dir:" cscope_pre
        if !empty(cscope_file) && filereadable(cscope_file)
            exe "cs add" cscope_file cscope_pre
        endif
    else "else search cscope.out elsewhere
        let cscope_file = findfile("cscope.out", ".;")
        let cscope_pre  = matchstr(cscope_file, ".*/")
        " echo "get cs file:" cscope_file
        " echo "get cs dir:" cscope_pre
        if !empty(cscope_file) && filereadable(cscope_file)
            exe "cs add" cscope_file cscope_pre
        endif
    endif
endif

"cscope插件热键
nmap <leader>fs :cs find s <C-R>=expand("<cword>")<CR><CR> :cw<CR>
" nmap <leader>fs :vert scs find s <C-R>=expand("<cword>")<CR><CR> :cw<CR>
nmap <leader>fg :cs find g <C-R>=expand("<cword>")<CR><CR>
nmap <leader>fc :cs find c <C-R>=expand("<cword>")<CR><CR>
nmap <leader>ft :cs find t <C-R>=expand("<cword>")<CR><CR>
nmap <leader>fe :cs find e <C-R>=expand("<cword>")<CR><CR>
nmap <leader>ff :cs find f 
nmap <leader>fv :cs find s 
nmap <leader>fi :cs find i <C-R>=expand("<cfile>")<CR><CR>
nmap <leader>fd :cs find d <C-R>=expand("<cword>")<CR><CR>

" 将quickfix窗口移动到窗口布局的底部
au fileType qf wincmd J

" 将quickfix窗口移动到窗口布局的左边
" au fileType qf wincmd H

" 横屏
nmap <leader>o :cw<CR>
" 竖屏
" nmap <leader>o :vert cw 90<CR>

nmap <c-a> :cp<CR> "向前选择quickfix
nmap <c-e> :cn<CR> "向后选择quickfix

"----------------------------------------
"rainbow.vim
"----------------------------------------
let g:rainbow_active = 1 " 彩虹括号, 0代表关闭
let g:rainbow_conf = {
            \   'guifgs': ['royalblue3', 'darkorange3', 'seagreen3', 'firebrick'],
            \   'ctermfgs': ['lightblue', 'lightyellow', 'lightcyan', 'lightmagenta'],
            \   'operators': '_,_',
            \   'parentheses': ['start=/(/ end=/)/ fold', 'start=/\[/ end=/\]/ fold', 'start=/{/ end=/}/ fold'],
            \   'separately': {
            \       '*': {},
            \       'tex': {
            \           'parentheses': ['start=/(/ end=/)/', 'start=/\[/ end=/\]/'],
            \       },
            \       'lisp': {
            \           'guifgs': ['royalblue3', 'darkorange3', 'seagreen3', 'firebrick', 'darkorchid3'],
            \       },
            \       'vim': {
            \           'parentheses': ['start=/(/ end=/)/', 'start=/\[/ end=/\]/', 'start=/{/ end=/}/ fold',
            \                           'start=/(/ end=/)/ containedin=vimFuncBody',
            \                           'start=/\[/ end=/\]/ containedin=vimFuncBody',
            \                           'start=/{/ end=/}/ fold containedin=vimFuncBody'],
            \       },
            \       'html': {
            \           'parentheses': ['start=/\v\<((area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|source|track|wbr)[ >])@!\z([-_:a-zA-Z0-9]+)(\s+[-_:a-zA-Z0-9]+(\=("[^"]*"|'."'".'[^'."'".']*'."'".'|[^ '."'".'"><=`]*))?)*\>/ end=#</\z1># fold'],
            \       },
            \       'css': 0,
            \       'txt': 0,
            \       'md': 0,
            \   }
            \}

"----------------------------------------
"NERDTree.vim
"----------------------------------------
nmap <F3> :NERDTreeToggle<CR>
"autocmd vimenter * NERDTree
autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTreeType") &&b:NERDTreeType == "primary") | q | endif

let g:NERDTreeWinPos="left"
let g:NERDTreeWinSize=32
"let g:NERDTreeQuitOnOpen=1
let g:NERDTreeShowLineNumbers=1
let g:neocomplcache_enable_at_startup = 1
"To update the NERDTree when change the Tab by gt
nnoremap <leader>gt gt:NERDTreeFind<CR><C-w>l

"----------------------------------------
"vim-nerdtree-syntax-highlight settings
"----------------------------------------
"Highlight full name (not only icons). You need to add this if you don't have vim-devicons and want highlight.
let g:NERDTreeFileExtensionHighlightFullName = 1
let g:NERDTreeExactMatchHighlightFullName = 1
let g:NERDTreePatternMatchHighlightFullName = 1

""Highlight full name (not only icons). You need to add this if you don't have
""vim-devicons and want highlight.
let g:NERDTreeHighlightFolders = 1

"highlights the folder name
let g:NERDTreeHighlightFoldersFullName = 1

" ""you can add these colors to your .vimrc to help customizing
let s:brown = "905532"
let s:aqua =  "3AFFDB"
let s:blue = "689FB6"
let s:darkBlue = "44788E"
let s:purple = "834F79"
let s:lightPurple = "834F79"
let s:red = "AE403F"
let s:beige = "F5C06F"
let s:yellow = "F09F17"
let s:orange = "D4843E"
let s:darkOrange = "F16529"
let s:pink = "CB6F6F"
let s:salmon = "EE6E73"
let s:green = "8FAA54"
let s:Turquoise = "40E0D0"
let s:lightGreen = "31B53E"
let s:white = "FFFFFF"
let s:rspec_red = "FE405F"
let s:git_orange = "F54D27"
let s:gray = "808A87"

let g:NERDTreeExtensionHighlightColor = {} " this line is needed to avoid error
let g:NERDTreeExtensionHighlightColor['o'] = s:gray " sets the color of o files to blue
let g:NERDTreeExtensionHighlightColor['h'] = s:blue " sets the color of h files to blue
let g:NERDTreeExtensionHighlightColor['c'] = s:green " sets the color of c files to blue
let g:NERDTreeExtensionHighlightColor['cpp'] = s:green " sets the color of cpp files to blue
let g:NERDTreeExtensionHighlightColor['c++'] = s:green " sets the color of c++ files to blue

"----------------------------------------
"nerdtree-git-plugin settings
"----------------------------------------
let g:NERDTreeGitStatusShowIgnored = 0 " a heavy feature may cost much more time. default: 0

let g:NERDTreeGitStatusIndicatorMapCustom = {
                \ 'Modified'  :'✹',
                \ 'Staged'    :'✚',
                \ 'Untracked' :'✭',
                \ 'Renamed'   :'➜',
                \ 'Unmerged'  :'═',
                \ 'Deleted'   :'✖',
                \ 'Dirty'     :'✗',
                \ 'Ignored'   :'☒',
                \ 'Clean'     :'✔︎',
                \ 'Unknown'   :'?',
                \ }

"----------------------------------------
"vim-trailing-whitespace'
"----------------------------------------
map <leader><space> :FixWhitespace<CR>

"mbbill/undotree
nnoremap <leader>u :UndotreeToggle<CR>
let g:undotree_SetFocusWhenToggle=1

"----------------------------------------
"vim-fugitive
"----------------------------------------
"TODO

"----------------------------------------
"vim-easymotion
"----------------------------------------
" 使用 EasyMotion 进行一键搜索
let g:EasyMotion_use_smartsign_us = 1
nmap <Leader>; <Plug>(easymotion-s)

" let g:EasyMotion_do_mapping = 1
let g:EasyMotion_smartcase = 1

" ` s ` Search character
" ` f ` Find character forwards
" ` F ` Find character backwards

"----------------------------------------
"vim-signify
"----------------------------------------
"default updatetime 4000ms is not good for async update
set updatetime=300
let g:signify_disable_by_default = 1     "默认关闭功能。
map <c-g> :SignifyToggle<CR>

"----------------------------------------
"autoformat "依赖clang-format, 需要安装它
"----------------------------------------
" let g:autoformat_verbosemode=1 "开启详细模式便于查错
" autocmd BufWrite *.sql,*.c,*.py,*.java,*.js :Autoformat "设置发生保存事件时执行格式化
" let g:autoformat_autoindent = 0
" let g:autoformat_retab = 0
" let g:autoformat_remove_trailing_spaces = 0
" autocmd FileType vim,tex let b:autoformat_autoindent=0
" gg=G :retab :RemoveTrailingSpaces
"/
" nmap <leader>format :Autoformat<CR>
"

nmap <leader>fmt :call FormatCode()<CR>
func! FormatCode()
    exec "w"
    if &filetype == 'C' || &filetype == 'h'
        exec "!astyle --style=linux --lineend=linux --convert-tabs --indent=spaces=4 --indent-namespaces --indent-preproc-block --indent-preproc-define --indent-preproc-cond --indent-col1-comments --unpad-paren --align-pointer=name --align-reference=name --pad-oper --pad-header -n %"
    elseif &filetype == 'cpp'
        exec "!astyle --style=google --lineend=linux --convert-tabs --indent=spaces=4 --indent-namespaces --indent-preproc-block --indent-preproc-define --indent-preproc-cond --indent-col1-comments --unpad-paren --align-pointer=name --align-reference=name --pad-oper --pad-header -n %"
        return
    endif
endfunc


"----------------------------------------
"clang-format "依赖clang-format, 需要安装它
"----------------------------------------
let g:clang_format#style_options = {
            \ "AccessModifierOffset" : -4,
            \ "AllowShortIfStatementsOnASingleLine" : "true",
            \ "AlwaysBreakTemplateDeclarations" : "true",
            \ "Standard" : "C++11"}

" map to <Leader>cf in C++ code
" autocmd FileType c,cpp,objc nnoremap <buffer><Leader>cf :<C-u>ClangFormat<CR>
autocmd FileType c,cpp,objc vnoremap <buffer><Leader>cf :ClangFormat<CR>
" if you install vim-operator-user
" autocmd FileType c,cpp,objc map <buffer><Leader>x <Plug>(operator-clang-format)
" Toggle auto formatting:
nmap <Leader>C :ClangFormatAutoToggle<CR>

"----------------------------------------
"Window Chooser
"----------------------------------------
"mapping
nmap = <Plug>(choosewin)
" show big letters
let g:choosewin_overlay_enable = 1

"----------------------------------------
"Ranger
"----------------------------------------
" 设置 Ranger.vim 为默认文件浏览器
let g:ranger_map_keys = 0
autocmd FileType ranger setlocal nonumber
autocmd FileType ranger nnoremap <buffer> <CR> :Ranger<CR>

" 设置 Ranger 窗口的默认宽度为30%
let g:ranger_winsize = 30

" 设置 Ranger 窗口位置为左侧
let g:ranger_window_layout = 'vertical'

" 设置 Ranger 窗口初始目录为当前文件所在目录
let g:ranger_start_from_vim_root = 0

" 设置光标在退出 Ranger 窗口时回到上一个焦点
let g:ranger_restore_window = 1
nnoremap <leader>e :Ranger<CR>
"----------------------------------------
"interestingwords
"----------------------------------------
let g:interestingWordsDefaultMappings = 1
let g:interestingWordsGUIColors = ['#8CCBEA', '#A4E57E', '#FFDB72', '#FF7272', '#FFB3FF', '#9999FF']
let g:interestingWordsTermColors = ['154', '121', '211', '137', '214', '222']
let g:interestingWordsRandomiseColors = 1
nnoremap <silent> <leader>k :call InterestingWords('n')<cr>
vnoremap <silent> <leader>k :call InterestingWords('v')<cr>
nnoremap <silent> <leader>K :call UncolorAllWords()<cr>

nnoremap <silent> n :call WordNavigation(1)<cr>
nnoremap <silent> N :call WordNavigation(0)<cr>

"----------------------------------------
"delete ^M
"----------------------------------------
nnoremap <leader>m :%s/[^[:print:]]$//g<CR>
nnoremap <leader>x :%s/\s*//g<CR>

"----------------------------------------
" 全局替换 \c:大小写不敏感；\C:大小写敏感
"----------------------------------------
nmap <leader>r   :%s/-\C/+/g
" nmap <leader>r   :%s/-/+/g

" Tab替换为空格
nmap <leader>tab :%retab!<CR>

" 显示行号 toggle
nmap <leader>n :set nu!<CR>

" paste 模式 toggle
nmap <leader>p :set paste!<CR>

"----------------------------------------
"close | save window
"----------------------------------------
nmap <leader>q :qa
nmap <leader>w :w<CR>
nmap <leader>1 :only<CR>
nmap <leader>2 :only<CR> :NERDTree<CR> <C-W>w
nmap <leader>3 :only<CR> :NERDTree<CR> :Tagbar<CR> <C-W>w <C-W>w


